// 回调时点击[Query]
function re_query(){
	$("[data-label='Query']").click();
}

$(document).on('page-change', function(e) {
	console.log(frappe.user);
});

frappe.pages['Reconciliation'].on_page_load = function(wrapper, reconciliation_billno) {
	var page = frappe.ui.make_app_page({
		parent: wrapper,
		title: 'None',
		single_column: true,
		reconciliation_billno: reconciliation_billno
	});

	page.set_title('对账');
	// frappe.user

	// let reconciliation_billno;
	console.log(`this is ${reconciliation_billno}`);

	let field = page.add_field({
		label: __('SRM AP Reconciliation'),
		fieldtype: 'Select',
		fieldname: 'reconciliation',
		options: ["", "123456789123456666-221214"],
		default: "",
		change() {
			reconciliation_billno = field.get_value();
		}
	});
	let field_outitems = page.add_field({
		label: __('Total OutItems'),
		fieldtype: 'Data',
		fieldname: 'total_outitems'
	});
	let field_returnitems = page.add_field({
		label: __('Total ReturnItems'),
		fieldtype: 'Data',
		fieldname: 'total_returnitems'
	});
	let field_expenseitems = page.add_field({
		label: __('Total ExpenseItems'),
		fieldtype: 'Data',
		fieldname: 'total_expenseitems'
	});
	let field_current_ap = page.add_field({
		label: __('Current AP'),
		fieldtype: 'Data',
		fieldname: 'current_ap'
	});


	let exec_query = function() {
		frappe.db.get_doc("SRM AP Reconciliation", reconciliation_billno)
			.then((r) => {
				// 填充数据r.outitems 到 data_outitems
				let data_outitems = [];
				if (r.outitems) {
					// forEach遍历r.outitems,只拿需要的数据
					r.outitems.forEach((i) => {
						let row_value = [];
						row_value.push(i.material_number+' : '+i.material_name,
										i.uom,
										i.srm_purchase_delivery,
										i.srm_purchase_order+' : '+i.purchase_order_seq,
										i.delivery_qty+' : '+i.delivery_amount,
										i.return_qty+' : '+i.return_amount,
										i.instock_qty+' : '+i.instock_amount,
										i.cur_check_qty,
										i.cur_check_amount,
										i.name);
						data_outitems.push(row_value);
					})
				}
				// 填充数据r.returnitems 到 data_returnitems
				let data_returnitems = [];
				if (r.returnitems) {
					// forEach遍历r.outitems,只拿需要的数据
					r.returnitems.forEach((i) => {
						let row_value = [];
						row_value.push(i.material_number+' : '+i.material_name,
										i.uom,
										i.srm_instock_return,
										i.srm_purchase_order+' : '+i.purchase_order_seq,
										i.return_qty, 
										i.return_amount,
										i.sign_qty+' : '+i.sign_amount,
										i.cur_check_qty,
										i.cur_check_amount,
										i.name);
						data_returnitems.push(row_value);
					})
				}
				// 填充数据r.expenseitems 到 data_expenseitems
				let data_expenseitems = [];
				if (r.expenseitems) {
					// forEach遍历r.outitems,只拿需要的数据
					r.expenseitems.forEach((i) => {
						let row_value = [];
						row_value.push(i.expense_billno,
										i.expense_type,
										i.expense_item,
										i.amount,
										i.cur_check_amount, 
										i.name);
						data_expenseitems.push(row_value);
					})
				}
				// 以data_outitems刷新datatable_outitems
				datatable_outitems.refresh(data_outitems, columns_outitems);
				datatable_returnitems.refresh(data_returnitems, columns_returnitems);
				datatable_expenseitems.refresh(data_expenseitems, columns_expenseitems);

				// 汇总字段
				$("[data-fieldname='total_outitems']").val(r.total_outitems);
				$("[data-fieldname='total_returnitems']").val(r.total_returnitems);
				$("[data-fieldname='total_expenseitems']").val(r.total_expenseitems);
				$("[data-fieldname='current_ap']").val(r.current_ap);
		})
	}

	let $btn_one = page.set_primary_action(__('Query'), function() {
		exec_query();
	})

	// let $btn_two = page.set_secondary_action(__('Refresh'), 
	// //use regular ajax api methods to fetch document data, then refresh
	// 	function() {
	// 		// let values = page.get_form_values();
	// 		console.log(datatable1.datamanager.getRows());
	// 		console.log(datatable1.getRows());
	// 	}
	// )

	// 第一段datatable #outitems
	$("<div id='outitems' style='margin-top:20px'><div>出货明细</div><div class='datatable'></div></div>").appendTo('.layout-main-section');
	let el_outitems = document.querySelector('#outitems');
	let button_formatter_outitems = (value,rowData) => {
		return `<button onclick="frappe.confirm('确认不参与本次对账?',
		() => {
			frappe.call({
				method: 'srm.srm.doctype.srm_ap_reconciliation.srm_ap_reconciliation.del_outitems',
				args: {doc_name: '${reconciliation_billno}', row_name: '${rowData[9].content}'},
				callback:re_query,
			})
		})">删除</button>`;
	}

	let columns_outitems = [{name:'物料',width:268}, 
					'单位', 
					{name:'送货单',width:138}, 
					{name:'订单',width:168}, 
					{name:'送货',width:128}, 
					{name:'验退',width:128}, 
					{name:'入库',width:128},
					{name:'对账数量',width:88},
					{name:'对账金额',width:88},
					{name:'', width:0},
					{name: '操作', focusable: false, format: button_formatter_outitems, width:58 },
				]
	let datatable_outitems = new frappe.DataTable(el_outitems, { columns: columns_outitems, data: [], layout: "flex", inlineFilters: true, serialNoColumn: false });

	// 第二段datatable #returnitems
	$("<div id='returnitems' style='margin-top:20px'><div>仓退明细</div><div class='datatable'></div></div>").appendTo('.layout-main-section');
	let el_returnitems = document.querySelector('#returnitems');
	let button_formatter_returnitems = (value,rowData) => {
		return `<button onclick="frappe.confirm('确认不参与本次对账?',
		() => {
			frappe.call({
				method: 'srm.srm.doctype.srm_ap_reconciliation.srm_ap_reconciliation.del_returnitems',
				args: {doc_name: '${reconciliation_billno}', row_name: '${rowData[9].content}'},
				callback:re_query,
			})
		})">删除</button>`;
	}

	let columns_returnitems = [{name:'物料',width:268}, 
					'单位', 
					{name:'退货单',width:138}, 
					{name:'订单',width:168}, 
					{name:'退货数量',width:128}, 
					{name:'退货金额',width:128}, 
					{name:'签收',width:128},
					{name:'对账数量',width:88},
					{name:'对账金额',width:88},
					{name:'', width:0},
					{name: '操作', focusable: false, format: button_formatter_returnitems, width:58 },
				]
	let datatable_returnitems = new frappe.DataTable(el_returnitems, { columns: columns_returnitems, data: [], layout: "flex", inlineFilters: true, serialNoColumn: false });


	// 第三段datatable #expenseitems
	$("<div id='expenseitems' style='margin-top:20px'><div>仓退明细</div><div class='datatable'></div></div>").appendTo('.layout-main-section');
	let el_expenseitems = document.querySelector('#expenseitems');
	let button_formatter_expenseitems = (value,rowData) => {
		return `<button onclick="frappe.confirm('确认不参与本次对账?',
		() => {
			frappe.call({
				method: 'srm.srm.doctype.srm_ap_reconciliation.srm_ap_reconciliation.del_expenseitems',
				args: {doc_name: '${reconciliation_billno}', row_name: '${rowData[5].content}'},
				callback:re_query,
			})
		})">删除</button>`;
	}

	let columns_expenseitems = [{name:'单号',width:268}, 
					{name:'类型',width:268}, 
					{name:'项目',width:268}, 
					{name:'金额',width:128}, 
					{name:'对账金额',width:128},
					{name:'', width:0},
					{name: '操作', focusable: false, format: button_formatter_expenseitems, width:168 },
				]
	let datatable_expenseitems = new frappe.DataTable(el_expenseitems, { columns: columns_expenseitems, data: [], layout: "flex", inlineFilters: true, serialNoColumn: false });
	$("<span id='reconciliation'>对账单号:</span>").appendTo("[data-fieldname='reconciliation']");
	$("<span id='outitems'>出货:</span>").appendTo("[data-fieldname='total_outitems']");
	$("<span id='returnitems'>仓退:</span>").appendTo("[data-fieldname='total_returnitems']");
	$("<span id='expenseitems'>费用:</span>").appendTo("[data-fieldname='total_expenseitems']");
	$("<span id='current_ap'>本次对账:</span>").appendTo("[data-fieldname='current_ap']");
}